package com.vhall.component.service.order.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vhall.component.dao.order.OrderDetailMapper;
import com.vhall.component.entity.order.OrderDetailEntity;
import com.vhall.component.entity.order.vo.OrderListReqVo;
import com.vhall.component.entity.order.vo.OrderPage;
import com.vhall.component.plugin.common.constant.ConstStr;
import com.vhall.component.service.order.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author guoxin.wang
 * @date 2021-07-05 10:38
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Override
    public OrderPage list(OrderListReqVo reqVO) {
        reqVO.setAppId(reqVO.getAppId());
        reqVO.setStatus(reqVO.getType() == null ? 0 : reqVO.getType());
        reqVO.setCurrPage(reqVO.getCurrPage() == null ? 1 : reqVO.getCurrPage());
        reqVO.setPageSize(reqVO.getPageSize() == null ? 20 : reqVO.getPageSize());
        LambdaQueryWrapper<OrderDetailEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(OrderDetailEntity::getStatus, reqVO.getStatus())
                .eq(OrderDetailEntity::getAppId, reqVO.getAppId())
                .eq(StringUtils.isNotBlank(reqVO.getAccountId()), OrderDetailEntity::getAccountId, reqVO.getAccountId())
                .ge(StringUtils.isNotBlank(reqVO.getStartTime()), OrderDetailEntity::getCreatedAt, reqVO.getStartTime())
                .le(StringUtils.isNotBlank(reqVO.getEndTime()), OrderDetailEntity::getCreatedAt, setReqEndTime(reqVO.getEndTime()))
                .orderByDesc(OrderDetailEntity::getCreatedAt);
        Page<OrderDetailEntity> page = new Page<>(reqVO.getCurrPage(), reqVO.getPageSize());
        page = orderDetailMapper.selectPage(page, wrapper);
        return new OrderPage<>(page);
    }

    @Override
    public Boolean create(OrderDetailEntity reqVO) {
        int insert = orderDetailMapper.insert(reqVO);
        return insert > 0;
    }

    public String setReqEndTime(String endTime) {
        if (StringUtils.isNotBlank(endTime)) {
            if (endTime.contains(ConstStr.TIME_ZERO)) {
                endTime = endTime.replace(ConstStr.TIME_ZERO, ConstStr.TIME_FULL);
            } else {
                endTime = endTime + " " + ConstStr.TIME_FULL;
            }
        }
        return endTime;
    }

}
